package com.zhs.gccs.fragment.gccs;

import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.annimon.stream.Stream;
import com.google.gson.Gson;
import com.hjq.shape.view.ShapeButton;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.zhs.gccs.R;
import com.zhs.gccs.activity.gccs.GccsUserTaskDataDetailActivity;
import com.zhs.gccs.adapter.GccsDataListAdapter;
import com.zhs.gccs.dao.TaskGccsDataDao;
import com.zhs.gccs.dao.TaskGccsFileDao;
import com.zhs.gccs.dialog.GccsDataSearchDialog;
import com.zhs.gccs.event.EventAddGccs;
import com.zhs.gccs.fragment.BaseFragment;
import com.zhs.gccs.http.Api;
import com.zhs.gccs.http.ProgressObserver;
import com.zhs.gccs.model.GccsDict;
import com.zhs.gccs.model.GccsTaskData;
import com.zhs.gccs.model.GccsTaskFile;
import com.zhs.gccs.utils.DialogUtils;
import com.zhs.gccs.utils.OnNoDoubleClickListener;
import com.zhs.gccs.utils.ScreenUtils;
import com.zhs.gccs.utils.ToastUtils;
import com.zhs.gccs.vo.ApplyGccsTask;
import com.zhs.gccs.vo.GccsDataStatistics;
import com.zhs.gccs.vo.GccsStatistics;
import com.zhs.gccs.vo.GctbListBean;
import com.zhs.gccs.vo.XmGccsDataStateBean;
import com.zhs.gccs.vo.XmGccsDeleteDataBean;
import com.zhs.gccs.vo.XmGccsStatisticsBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.RequestBody;

public class GccsDataListFragment extends BaseFragment {
    @BindView(R.id.view_search_param)
    View view_search_param;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_gccs)
    TextView  tv_gccs;
    private String gccsType;
    @BindView(R.id.tv_problem)
    TextView tv_problem;
    private String problem;
    @BindView(R.id.iv_search)
    View  iv_search;
    @BindView(R.id.tv_save)
    View  tv_save;
    private List<GccsTaskData> taskDataList;
    private GccsDataListAdapter gccsTaskAdapter;
    private int pageNum = 0;
    private int pageSize = 10000;
    private TaskGccsDataDao taskGccsDataDao;
    private TaskGccsFileDao taskGccsFileDao;
    GccsStatistics gccsStatistics;
    ApplyGccsTask taskBean;
    @Override
    protected int getLayout() {
        return R.layout.fragment_gccs_list;
    }

    public static GccsDataListFragment newInstance(ApplyGccsTask bean) {
        Bundle args = new Bundle();
        args.putSerializable("task", bean);
        GccsDataListFragment fragment = new GccsDataListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        taskBean = (ApplyGccsTask) getArguments().getSerializable("task");
        taskGccsDataDao = new TaskGccsDataDao();
        taskGccsFileDao = new TaskGccsFileDao();
        taskDataList = new ArrayList<>();
        gccsTaskAdapter = new GccsDataListAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(gccsTaskAdapter);

        gccsTaskAdapter.setOperationListener(new GccsDataListAdapter.ItemOperationListener() {
            @Override
            public void onDelete(GccsTaskData bean) {
                DialogUtils.showPromote2(context, "确认删除?", null, new DialogUtils.OnConfirmListener() {
                    @Override
                    public void onConfirmed() {
                        toDeleteData(bean);
                    }
                });
            }

            @Override
            public void onItemClick(GccsTaskData bean) {
                GccsUserTaskDataDetailActivity.start(getActivity(),
                        bean.getId(),taskBean,gccsStatistics);
            }
        });

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                pageNum = 0;
                getData();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
//                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
                getData();
            }
        });

        gccsType = "";
        problem = "";


        view_search_param.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                new GccsDataSearchDialog.Builder(getActivity(), gccsStatistics, gccsType, problem, new GccsDataSearchDialog.OnSelectedListener() {
                    @Override
                    public void onSelected(String gccs, String prob) {
                        gccsType = gccs;
                        problem = prob;
                        pageNum = 0;
                        getData();
                    }
                }).show();
            }
        });

        tv_save.setOnClickListener(new OnNoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                toSubmitData();
            }
        });

        getData();
        getXmGccsTypesData();
        if(taskBean!=null){
            if("20".equals(taskBean.getState())){
                tv_save.setVisibility(View.GONE);
            }
        }
    }



    private Dialog bottomDialog(View view) {
//        View view = LayoutInflater.from(this).inflate(layout, null);
        Dialog dialog = new Dialog(this.getActivity());
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setContentView(view);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = (int) (ScreenUtils.dpToPx(context, ScreenUtils.getScreenWidthDp(context)) * 1);//WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = (int) (ScreenUtils.getScreenHeightPx(context) * 0.6);// WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);
        //dialog.show();
        return dialog;
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventAddGccs event) {
         //重新加载数据
        pageNum = 0;
        getData();
        getXmGccsTypesData();
    }

    private void getData() {
        toSubscribeSingleOb(Api.getDefault()
                        .xmGccsList(taskBean.getPid(),gccsType,problem, pageSize, pageNum),
                new ProgressObserver(this.getActivity(), false) {
                    @Override
                    protected void _onNext(String result) {
//                        GccsTaskDataPageListBean bean = JSON.parseObject(result, GccsTaskDataPageListBean.class);
                        GctbListBean bean = new Gson().fromJson(result, GctbListBean.class);
                        if (pageNum == 0) {
                            taskDataList.clear();
                        }
                        if (bean != null && bean.getCode() == 200 &&
                                bean.getRows() != null && bean.getRows().size() > 0) {
                            List<GccsTaskData> rows = bean.getRows();
                            taskDataList.addAll(rows);
                            Stream.of(rows).forEach(item->{
                                taskGccsDataDao.addOrUpdate(item);
                                if(item.getFileList()!=null&&item.getFileList().size()>0){
                                }else{
                                    //用本地缓存的作为
                                    List<GccsTaskFile> taskFiles = taskGccsFileDao.
                                            findByDataId(item.getId());
                                    item.setFileList(taskFiles);
                                }
                            });
                            finishLoadMore();
                            int total = bean.getTotal();
                            if (total > ((pageNum + 1) * pageSize)) {
                                ++pageNum;
                                refreshLayout.setEnableLoadMore(true);
                            } else {
                                refreshLayout.setEnableLoadMore(false);
                            }
                        } else {
                            finishLoadMore();
                            refreshLayout.setEnableLoadMore(false);
                        }
                        gccsTaskAdapter.setNewData(taskDataList);
                    }

                    @Override
                    protected void _onError(String result) {
                        finishLoadMore();
                        refreshLayout.setEnableLoadMore(false);
                    }
                });
    }

    private void finishLoadMore() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
    }

    private void getXmGccsTypesData() {
        toSubscribeSingleOb(Api.getDefault().
                        getXmGccsStatistics(taskBean.getPid()),
                new ProgressObserver(this.getActivity(), false) {
                    @Override
                    protected void _onNext(String result) {
                        XmGccsStatisticsBean bean = new Gson().fromJson(result, XmGccsStatisticsBean.class);//GsonImpl.get().toObject(result, SmTaskBean.class);
                        if (bean != null && bean.getCode() == 200) {
                            gccsStatistics = bean.getData();
                            if(gccsStatistics.getXmGccs()!=null){
                                Stream.of(gccsStatistics.getXmGccs()).forEach(xmgccs->{
                                    if(gccsStatistics.getGccs()!=null){
                                        GccsDict gccs = Stream.of(gccsStatistics.getGccs()).
                                                filter(i -> xmgccs.getDbid().equals(i.getDbid())).findFirstOrElse(null);
                                        if(gccs!=null){
                                            xmgccs.setTypeName(gccs.getMc2());
                                            xmgccs.setInt("1".equals(gccs.getIsInt()));
                                        }
                                    }
                                    if (gccsStatistics.getXmGccsReport() != null) {
                                        GccsDataStatistics report = Stream.of(gccsStatistics.getXmGccsReport()).
                                                filter(i -> xmgccs.getDbid().equals(i.getDbid())).findFirstOrElse(null);
                                        if (report != null) {
                                            xmgccs.setReportCount(report.getRwl());
                                        }
                                    }
                                });
//                                gccsSingleSelectView.initData(gccsStatistics.getXmGccs());
                            }
                        } else {

                        }
                    }
                    @Override
                    protected void _onError(String result) {
                        Log.e("_onError",result);
                    }
                });
    }

    private void toDeleteData(GccsTaskData bean) {
        Map hashMap = new HashMap();
        hashMap.put("id",bean.getId());
        RequestBody requestBody = createRequestBody(hashMap);
        toSubscribeSingleOb(Api.getDefault().
                        gccsDeleteData(requestBody),
                new ProgressObserver(this.getActivity(), false) {
                    @Override
                    protected void _onNext(String result) {
                        XmGccsDeleteDataBean deleteDataBean = new Gson().fromJson(result, XmGccsDeleteDataBean.class);//GsonImpl.get().toObject(result, SmTaskBean.class);
                        if (deleteDataBean != null && deleteDataBean.getCode() == 200) {
                            ToastUtils.toast("删除成功");
                            pageNum = 0;
                            taskGccsDataDao.deleteById(bean.getId());
                            taskGccsFileDao.deleteByDataId(bean.getId());
                            getData();
                            EventBus.getDefault().post(new EventAddGccs());
                        } else {
                            ToastUtils.toast("删除失败");
                        }
                    }
                    @Override
                    protected void _onError(String result) {
                        Log.e("_onError",result);
                    }
                });
    }

    private void toSubmitData() {
        showDialog();
        Map hashMap = new HashMap();
        hashMap.put("id",taskBean.getId());
        hashMap.put("state","20");
        RequestBody requestBody = createRequestBody(hashMap);
        toSubscribeSingleOb(Api.getDefault().
                        updateGccsTaskState(requestBody),
                new ProgressObserver(this.getActivity(), false) {
                    @Override
                    protected void _onNext(String result) {
                        dismissDialog();
                        XmGccsDataStateBean deleteDataBean = new Gson().fromJson(result, XmGccsDataStateBean.class);//GsonImpl.get().toObject(result, SmTaskBean.class);
                        if (deleteDataBean != null && deleteDataBean.getCode() == 200) {
                            ToastUtils.toast("提交成功");
                            taskBean.setState("20");
                            tv_save.setVisibility(View.GONE);
                        } else {
                            ToastUtils.toast("提交失败");
                        }
                    }
                    @Override
                    protected void _onError(String result) {
                        dismissDialog();
                        Log.e("_onError",result);
                    }
                });
    }
}
